// Copy from "element-ui/lib/transitions/collapse-transition"
import { ComponentOptions } from "vue";
import { addClass, removeClass } from './mob';

import "./style.scss";

export const CollapseTransitionName = 'CollapseTransition';

export default <ComponentOptions<Vue>>{
  name: 'CollapseTransition',
  functional: true,
  render(h, { props, children }) {
    const transition_class = 'collapse-transition';
    const open_animation: boolean | undefined = props.value;
    return h('transition', {
      on: {
        beforeEnter: (el: HTMLElement) => {
          if (!el.dataset) (el as any).dataset = {};
          el.dataset.oldPaddingTop = el.style.paddingTop;
          el.dataset.oldPaddingBottom = el.style.paddingBottom;
          if (open_animation) {
            addClass(el, transition_class);
            el.style.height = '0';
            el.style.paddingTop = '0';
            el.style.paddingBottom = '0';
          }
        },
        enter(el: HTMLElement) {
          if (!open_animation) {
            return;
          }
          el.dataset.oldOverflow = el.style.overflow;
          if (el.scrollHeight !== 0) {
            el.style.height = el.scrollHeight + 'px';
            el.style.paddingTop = el.dataset.oldPaddingTop || '';
            el.style.paddingBottom = el.dataset.oldPaddingBottom || '';
          } else {
            el.style.height = '';
            el.style.paddingTop = el.dataset.oldPaddingTop || '';
            el.style.paddingBottom = el.dataset.oldPaddingBottom || '';
          }
          el.style.overflow = 'hidden';
        },
        afterEnter(el: HTMLElement) {
          // for safari: remove class then reset height is necessary
          removeClass(el, transition_class);
          el.style.height = '';
          el.style.overflow = el.dataset.oldOverflow || '';
        },
        beforeLeave(el: HTMLElement) {
          if (!el.dataset) (el as any).dataset = {};
          el.dataset.oldPaddingTop = el.style.paddingTop;
          el.dataset.oldPaddingBottom = el.style.paddingBottom;
          el.dataset.oldOverflow = el.style.overflow;
          el.style.height = el.scrollHeight + 'px';
          el.style.overflow = 'hidden';
        },
        leave(el: HTMLElement) {
          if (el.scrollHeight !== 0) {
            // for safari: add class after set height, or it will jump to zero height suddenly, weired
            if (open_animation) {
              addClass(el, transition_class);
            }
            el.style.height = '0';
            el.style.paddingTop = '0';
            el.style.paddingBottom = '0';
          }
        },
        afterLeave(el: HTMLElement) {
          removeClass(el, transition_class);
          el.style.height = '';
          el.style.overflow = el.dataset.oldOverflow || '';
          el.style.paddingTop = el.dataset.oldPaddingTop || '';
          el.style.paddingBottom = el.dataset.oldPaddingBottom || '';
        }
      }
    }, children);
  }
};
